package com.jzoom.zoom.admin.interceptors;

import com.jzoom.zoom.admin.models.AuthService;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.token.TokenService;
import com.jzoom.zoom.token.hex.ClientToken;
import com.jzoom.zoom.web.action.ActionContext;
import com.jzoom.zoom.web.action.ActionInterceptorAdapter;
import com.jzoom.zoom.web.exception.StatusException;

import javax.servlet.http.HttpServletRequest;

public class AdminActionInterceptor extends ActionInterceptorAdapter {
	
	@Inject
	private TokenService tokenService;

	@Inject(value = "admin")
	private Dao dao;
	
	
	
	
	@Inject
	private AuthService authService;
	
	
	
	//private static final Pattern URL_PATTERN = Pattern.compile("([a-zA-Z0-9]+)\\/[^add|index|find|put|del|edit$][\\/[a-zA-Z0-9-]+]*");

    private String getToken(ActionContext context) {
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("token");
        if (token != null) {
            return token;
        }

        Object param = context.getPreParam();
        if (param instanceof HttpServletRequest) {
            //也接受来自表单的token
            token = (String) request.getParameter("_token");
            if (token != null) {
                return token;
            }
        }

        return null;
    }

	@Override
    public void parse(ActionContext context) throws Exception {
        String token = getToken(context);

        ClientToken clientToken = tokenService.verifyToken(token);

        if (clientToken == null) {
            throw new StatusException.UnAuthException();
        }

        if (clientToken.isTimeout()) {
            throw new StatusException.UnAuthException();
        }


        //检查权限是否满足条件
        String[] moduleIds = authService.checkAuth(clientToken, context, clientToken.getId());
        context.put("token", clientToken);
        context.put("userId", clientToken.getId());
        context.put("mods", moduleIds);
    }

    @Override
    public boolean preParse(ActionContext context) throws Exception {

        String path = context.getRequest().getServletPath();
        if (path.startsWith("/public") || path.startsWith("/static")) {
            return true;
        }


        return true;
    }
}
